<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-08-02
 * Time: 14:34
 */

namespace App\Services;

use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use App\Repositories\UserLoginLogRepository;

class UserLoginLogService
{
    /**
     * @var UserLoginLogRepository 注入的UserLoginLogRepository
     */
    protected $user_loginLog_repository;

    /**
     * UserLoginLogService constructor.
     * @param UserLoginLogRepository $userLoginLogRepository
     */
    public function __construct(UserLoginLogRepository $userLoginLogRepository){
        $this->user_loginLog_repository = $userLoginLogRepository;
    }

    /**
     * 生成用户登录记录
     * @return mixed
     */
    public function userLogin(){

        $ip = getClientIp();
        $address = [];//getClientCity($ip);
        $addressJson = $address ? \GuzzleHttp\json_encode($address) : '';

        $userId = data_get(Auth::user(), 'id');

        $data = ['userId' => $userId,
            'lastLoginTime' => Carbon::now(),
            'lastLoginIp' => $ip,
            'loginCity' => data_get($address, 'city'),
            'address_data' => $addressJson];

        return $this->user_loginLog_repository->userLogin($data);
    }

    /**
     * 获取用户登录列表
     * @param array $data
     * @return mixed
     */
    public function getUserLoginLogPage(array $data){
        $arrData = $this->handleFilterUserCondition($data);
        $limit = data_get($data, 'limit');

        return $this->user_loginLog_repository->getUserLoginLogPage($arrData, $limit);
    }

    /**
     * 处理筛选参数
     * @param array $data
     * @return array
     */
    public function handleFilterUserCondition(array $data){

        /**
         * 处理筛选数据 TODO 模糊搜索
         * 使用包tucker-eric/eloquentfilter 已移除
         * https://packagist.org/packages/tucker-eric/eloquentfilter
         */
        $timeData = [];
        $userData = [];
        data_get($data, 'username') && array_push($userData, ['username', 'like', $data['username'] . '%']);
        data_get($data, 'realname') && array_push($userData, ['realname', 'like', $data['realname'] . '%']);
        data_get($data, 'mobile') && array_push($userData, ['mobile', 'like', $data['mobile'] . '%']);
        data_get($data, 'gender') && array_push($userData, ['gender', $data['gender']]);
        data_get($data, 'user_type') && array_push($userData, ['user_type', $data['user_type']]);

        //TODO 时间处理
        data_get($data, 'start_time') && array_push($timeData, ['login_time', '>=', utc_date($data['start_time'])]);
        data_get($data, 'end_time') && array_push($timeData, ['login_time', '<=', utc_date($data['end_time'])]);

        return ['user'=>$userData, 'time'=>$timeData];
    }
}